import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:seedfour/app/routes/app_routes.dart';
import 'package:seedfour/app/theme.dart';
import 'package:seedfour/app/views/module_case/case_create/logic.dart';
import 'package:seedfour/app/widget/tag.dart';

import '../../../constants.dart';
import '../../../models/case_list_entity.dart';
import '../../../widget/null_tip.dart';
import 'logic.dart';

class CasePage extends StatelessWidget {
  CasePage({Key? key}) : super(key: key);

  final logic = Get.find<CaseLogic>();

  @override
  Widget build(BuildContext context) {
    return Obx(
      () => Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          title:
              logic.isSearching.value ? _buildSearchField() : const Text('案件'),
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios,
              size: 16.w,
            ),
            onPressed: () {
              Get.back();
            },
          ),
          bottom: TabBar(
            controller: logic.tabController,
            tabs: logic.tabTitles.map((e) => Tab(text: e)).toList(),
          ),
          // 创建收款订单按钮
          actions: [
            if (!logic.isSearching.value) ...[
              IconButton(
                onPressed: () => {logic.onClickSearch()},
                icon: SvgPicture.asset(
                  'assets/icons/ic_search.svg',
                  width: kIconSizeTiny,
                ),
              ),
              IconButton(
                onPressed: () =>
                    Get.toNamed(RouteGet.caseCreate, arguments: CaseCreatePageType.create),
                icon: const Icon(Icons.add),
              ),
            ]
          ],
        ),
        body: logic.isLoading.value
            ? const Center(child: CircularProgressIndicator())
            : RefreshIndicator(
                onRefresh: () async => logic.reload(),
                child: Stack(
                  children: [
                    ListView.builder(
                      physics: const AlwaysScrollableScrollPhysics(),
                      controller: logic.scrollController,
                      itemBuilder: _renderRow,
                      itemCount: logic.caseList.length + 1,
                    ),
                    if (logic.isSearching.value && !logic.isSearched.value)
                      Container(
                        width: double.maxFinite,
                        height: double.maxFinite,
                        color: const Color(0x55000000),
                      ),
                  ],
                ),
              ),
      ),
    );
  }

  Widget _buildSearchField() {
    return Container(
      height: 40.w,
      margin: EdgeInsets.only(right: kSpaceMedium),
      child: TextField(
        autofocus: true,
        controller: logic.searchController,
        keyboardType: TextInputType.text,
        textInputAction: TextInputAction.search,
        onSubmitted: (value) => logic.onSearch(),
        onTap: () => logic.onClickSearch(),
        decoration: InputDecoration(
          prefixIcon: IconButton(
            icon: SvgPicture.asset(
              'assets/icons/ic_search.svg',
              width: kIconSizeTiny,
              height: kIconSizeTiny,
            ),
            onPressed: () => logic.onSearch(),
          ),
          suffixIcon: IconButton(
            iconSize: kIconSizeTiny,
            icon: const Icon(Icons.close),
            onPressed: () => logic.onCancelSearch(),
          ),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(kRadiusMedium),
            borderSide: const BorderSide(color: AppColor.colorBorderGrey),
          ),
          hintText: '案件名关键词',
          hintStyle: TextStyle(
            fontSize: kFontSizeSmall,
            color: AppColor.colorFontHint,
          ),
          contentPadding:
              EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.w),
        ),
      ),
    );
  }

  Widget _getMoreWidget() {
    return Center(
      child: Padding(
        padding: EdgeInsets.all(kSpaceMedium),
        child: Text(
          logic.bottomTips.value,
          style: TextStyle(fontSize: kFontSizeSmall, color: Colors.grey),
        ),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    if (index < logic.caseList.length) {
      return Container(
        margin: EdgeInsets.only(
          left: kSpaceSmall,
          right: kSpaceSmall,
          top: kSpaceMedium,
        ),
        child: Ink(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(kRadiusMedium),
          ),
          child: InkWell(
            borderRadius: BorderRadius.circular(kRadiusMedium),
            onTap: () => logic.onClickItem(index),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: kSpaceMedium),
                _buildItem('案件名称', logic.caseList[index].caseNameStr ?? ''),
                SizedBox(height: kSpaceMedium),
                _buildItem('案件类型', logic.caseList[index].caseTypeStr ?? ''),
                SizedBox(height: kSpaceMedium),
                _buildItem(
                    '案件状态', caseStatus[logic.caseList[index].caseStatus] ?? ''),
                SizedBox(height: kSpaceMedium),
                const Divider(),
                SizedBox(height: kSpaceMedium),
                _buildTags(logic.caseList[index]),
                SizedBox(height: kSpaceMedium),
              ],
            ),
          ),
        ),
      );
    } else if (logic.caseList.isEmpty) {
      return Column(
        children: [
          SizedBox(height: kSpaceHuge),
          const NullTip(),
        ],
      );
    } else {
      return _getMoreWidget();
    }
  }

  Widget _buildItem(String label, String value) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: kSpaceMedium),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: TextStyle(
              fontSize: kFontSizeSmall,
              color: AppColor.colorFontBlack,
            ),
          ),
          SizedBox(width: kSpaceMedium),
          Expanded(
            child: Text(
              textAlign: TextAlign.right,
              value,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                fontSize: kFontSizeSmall,
                color: AppColor.colorFontBlack,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTags(CaseInfo item) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        SizedBox(width: kSpaceMedium),
        if (item.cico != null && item.cico?.cStatus == 1) ...[
          _buildOrangeTag('合同已上传'),
          SizedBox(width: kSpaceMedium),
        ] else ...[
          _buildOrangeTag('合同未上传'),
          SizedBox(width: kSpaceMedium),
        ],
        if (item.cico != null && item.cico?.oStatus == 1) ...[
          _buildOrangeTag('订单已关联'),
          SizedBox(width: kSpaceMedium),
        ] else ...[
          _buildOrangeTag('订单未关联'),
          SizedBox(width: kSpaceMedium),
        ],
        if (item.cico != null)
          item.cico?.iStatus == 2
              ? _buildOrangeTag('发票已开出')
              : item.cico?.iStatus == 1
                  ? _buildOrangeTag('发票已填')
                  : _buildOrangeTag('发票未填'),
      ],
    );
  }

  Widget _buildOrangeTag(String text) {
    return Tag(
      text: text,
      textSize: kFontSizeMini,
      textColor: AppColor.colorFontOrange,
      padding: EdgeInsets.all(6.w),
      backgroundColor: const Color(0xFFFFF4F2),
    );
  }
}
